package com.sjb.cp.service.impl;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.sjb.cp.api.aliyun.model.CreateOutPaintingTaskRequest;
import com.sjb.cp.api.aliyun.model.CreateOutPaintingTaskResponse;
import com.sjb.cp.api.aliyun.sub.AliYunAiApi;
import com.sjb.cp.common.DeleteRequest;
import com.sjb.cp.common.ResultUtils;
import com.sjb.cp.exception.BusinessException;
import com.sjb.cp.exception.ErrorCode;
import com.sjb.cp.exception.ThrowUtils;
import com.sjb.cp.manager.CosManager;
import com.sjb.cp.manager.FileManager;
import com.sjb.cp.manager.upload.FilePictureUpload;
import com.sjb.cp.manager.upload.PictureUploadTemplate;
import com.sjb.cp.manager.upload.UrlPictureUpload;
import com.sjb.cp.model.constant.UserConstant;
import com.sjb.cp.model.dto.file.UploadPictureResult;
import com.sjb.cp.model.enums.PictureReviewStatusEnum;
import com.sjb.cp.model.po.Picture;
import com.sjb.cp.model.po.Space;
import com.sjb.cp.model.po.User;
import com.sjb.cp.model.request.picture.*;
import com.sjb.cp.model.vo.PictureVO;
import com.sjb.cp.model.vo.UserVo;
import com.sjb.cp.service.PictureService;
import com.sjb.cp.mapper.PictureMapper;
import com.sjb.cp.service.SpaceService;
import com.sjb.cp.service.UserService;
import com.sjb.cp.utils.ColorSimilarUtils;
import lombok.extern.slf4j.Slf4j;
import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.nodes.Element;
import org.jsoup.select.Elements;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.support.TransactionTemplate;
import org.springframework.util.CollectionUtils;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.socket.WebSocketSession;
import springfox.documentation.spring.web.json.Json;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.awt.*;
import java.io.IOException;
import java.util.*;
import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

/**
 * @author dell
 * @description 针对表【picture(图片)】的数据库操作Service实现
 * @createDate 2024-12-12 14:42:43
 */
@Service
@Slf4j
public class PictureServiceImpl extends ServiceImpl<PictureMapper, Picture>
        implements PictureService {

    @Resource
    private UserService userService;

    @Resource
    private FilePictureUpload filePictureUpload;

    @Resource
    private UrlPictureUpload urlPictureUpload;
    @Autowired
    private CosManager cosManager;

    @Resource
    private SpaceService spaceService;

    @Resource
    private TransactionTemplate transactionTemplate;

    //@Resource
    private ThreadPoolExecutor threadPoolExecutor;

    @Resource
    private AliYunAiApi aliYunAiApi;

    /**
     * 上传图片服务
     *
     * @param pictureUploadRequest
     * @param loginUser
     * @return
     */
    @Override
    @Transactional
    public PictureVO uploadPicture(Object inputResource, PictureUploadRequest pictureUploadRequest,
                                   User loginUser) {
        ThrowUtils.throwIf(loginUser == null, ErrorCode.NO_AUTH_ERROR);
        if (inputResource == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片不能为空");
        }
        Long pictureId = null;
        // 查询是新增还是修改
        if (pictureUploadRequest.getId() != null) {
            pictureId = pictureUploadRequest.getId();
            boolean exists = this.lambdaQuery().eq(Picture::getId, pictureId).exists();
            ThrowUtils.throwIf(!exists, ErrorCode.NOT_FOUND_ERROR);
        }
        Long spaceId = pictureUploadRequest.getSpaceId();

        // 如果是更新图片，需要校验图片是否存在
        if (pictureId != null) {
            Picture oldPicture = this.getById(pictureId);
            /*ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR, "图片不存在");
            // 仅本人或管理员可编辑
            if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }*/
            // 检验空间是否一致
            // 没传spaceId，则复用原有的spaceId
            if (spaceId == null) {
                if (oldPicture.getSpaceId() != null) {
                    spaceId = oldPicture.getSpaceId();
                }
            } else {
                // 传了spaceId，保持和原有的一致
                if (ObjectUtil.notEqual(spaceId, oldPicture.getSpaceId())) {
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "和原有空间不一致");
                }
            }
        }

        if (spaceId != null) {
            Space querySpace = spaceService.getById(spaceId);
            if (querySpace == null) {
                throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在");
            }
            // 必须空间管理人/创建人才能上传
           /* Long userId = querySpace.getUserId();
            if (!loginUser.getId().equals(userId)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "没有空间权限");
            }*/
            // 校验额度
            if (querySpace.getTotalCount() >= querySpace.getMaxCount()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间条数不足");
            }
            if (querySpace.getTotalSize() >= querySpace.getMaxSize()) {
                throw new BusinessException(ErrorCode.OPERATION_ERROR, "空间大小不足");
            }
        }

        // 新增 根据用户id划分目录
        String uploadFilePathPre = null;
        if (spaceId != null) {
            // 按照空间来划分目录
            uploadFilePathPre = String.format("space/%s", spaceId);
        } else {
            uploadFilePathPre = String.format("public/%s", loginUser.getId());
        }
        PictureUploadTemplate pictureUploadTemplate = filePictureUpload;
        if (inputResource instanceof String) {
            pictureUploadTemplate = urlPictureUpload;
        }
        UploadPictureResult uploadPictureResult = pictureUploadTemplate.uploadPicture(inputResource, uploadFilePathPre);
        if (StrUtil.isEmpty(pictureUploadRequest.getPicName())) {
            uploadPictureResult.setPicName(uploadPictureResult.getPicName());
        }
        // 入库
        Picture picture = new Picture();
        picture.setUrl(uploadPictureResult.getUrl());
        picture.setName(uploadPictureResult.getPicName());
        picture.setPicSize(uploadPictureResult.getPicSize());
        picture.setPicWidth(uploadPictureResult.getPicWidth());
        picture.setPicHeight(uploadPictureResult.getPicHeight());
        picture.setPicScale(uploadPictureResult.getPicScale());
        picture.setPicFormat(uploadPictureResult.getPicFormat());
        picture.setUserId(loginUser.getId());
        picture.setThumbnailUrl(uploadPictureResult.getThumbnailUrl());
        picture.setName(uploadPictureResult.getPicName());
        picture.setSpaceId(spaceId);

        if (pictureId != null) {
            // pictureId 不为空 更新
            picture.setId(pictureId);
            picture.setEditTime(new Date());
        }
        // 填充审核参数
        fillReviewParams(picture, loginUser);
        Long finalSpaceId = spaceId;
        transactionTemplate.execute(status -> {
            boolean saved = this.saveOrUpdate(picture);
            ThrowUtils.throwIf(!saved, ErrorCode.NOT_FOUND_ERROR, "图片上传失败");

            // 更新额度
            if (finalSpaceId != null) {
                boolean updated = spaceService.lambdaUpdate().eq(Space::getId, finalSpaceId)
                        .setSql("totalSize = totalSize + " + picture.getPicSize())
                        .setSql("totalCount = totalCount + 1")
                        .update();
                ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "额度更新失败");
            }
            return picture;
        });
        return PictureVO.ObjToVo(picture);
    }

    @Override
    public QueryWrapper<Picture> getQueryWrapper(PictureQueryRequest pictureQueryRequest) {
        QueryWrapper<Picture> queryWrapper = new QueryWrapper<>();
        if (pictureQueryRequest == null) {
            return queryWrapper;
        }
        // 从对象中取值
        // 从对象中取值
        Long id = pictureQueryRequest.getId();
        String name = pictureQueryRequest.getName();
        String introduction = pictureQueryRequest.getIntroduction();
        String category = pictureQueryRequest.getCategory();
        List<String> tags = pictureQueryRequest.getTags();
        Long picSize = pictureQueryRequest.getPicSize();
        Integer picWidth = pictureQueryRequest.getPicWidth();
        Integer picHeight = pictureQueryRequest.getPicHeight();
        Double picScale = pictureQueryRequest.getPicScale();
        String picFormat = pictureQueryRequest.getPicFormat();
        String searchText = pictureQueryRequest.getSearchText();
        String sortFiled = pictureQueryRequest.getSortFiled();
        Long userId = pictureQueryRequest.getUserId();
        String sortOrder = pictureQueryRequest.getSortOrder();
        Long spaceId = pictureQueryRequest.getSpaceId();
        boolean nullSpaceId = pictureQueryRequest.isNullSpaceId();
        Date startTime = pictureQueryRequest.getStartTime();
        Date endTime = pictureQueryRequest.getEndTime();

        // 从多字段中搜索
        if (StrUtil.isNotBlank(searchText)) {
            // 需要拼接查询条件
            queryWrapper.and(qw -> qw.like("name", searchText)
                    .or()
                    .like("introduction", searchText)
            );
        }

        queryWrapper.eq(ObjUtil.isNotEmpty(id), "id", id);
        queryWrapper.eq(ObjUtil.isNotEmpty(userId), "userId", userId);
        queryWrapper.like(StrUtil.isNotBlank(name), "name", name);
        queryWrapper.like(StrUtil.isNotBlank(introduction), "introduction", introduction);
        queryWrapper.like(StrUtil.isNotBlank(picFormat), "picFormat", picFormat);
        queryWrapper.eq(StrUtil.isNotBlank(category), "category", category);
        queryWrapper.eq(ObjUtil.isNotEmpty(picWidth), "picWidth", picWidth);
        queryWrapper.eq(ObjUtil.isNotEmpty(picHeight), "picHeight", picHeight);
        queryWrapper.eq(ObjUtil.isNotEmpty(picSize), "picSize", picSize);
        queryWrapper.eq(ObjUtil.isNotEmpty(picScale), "picScale", picScale);
        queryWrapper.eq(ObjUtil.isEmpty(spaceId), "spaceId", spaceId);
        queryWrapper.isNull(nullSpaceId, "nullSpaceId");
        queryWrapper.ge(ObjUtil.isNotNull(startTime), "startTime", startTime);
        queryWrapper.le(ObjUtil.isNotNull(endTime), "endTime", endTime);

        Integer reviewStatus = pictureQueryRequest.getReviewStatus();
        String reviewMessage = pictureQueryRequest.getReviewMessage();
        Long reviewerId = pictureQueryRequest.getReviewerId();
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewStatus), "reviewStatus", reviewStatus);
        queryWrapper.like(StrUtil.isNotBlank(reviewMessage), "reviewMessage", reviewMessage);
        queryWrapper.eq(ObjUtil.isNotEmpty(reviewerId), "reviewerId", reviewerId);

        // JSON 数组查询
        if (CollUtil.isNotEmpty(tags)) {
            for (String tag : tags) {
                queryWrapper.like("tags", "\"" + tag + "\"");
            }
        }

        // 排序
        queryWrapper.orderBy(StrUtil.isNotEmpty(sortFiled), sortOrder.equals("ascend"), sortFiled);
        return queryWrapper;
    }


    @Override
    public PictureVO getPictureVO(Picture picture, HttpServletRequest request) {
        // 对象转封装类
        PictureVO pictureVO = PictureVO.ObjToVo(picture);
        // 关联查询用户信息
        Long userId = picture.getUserId();
        if (userId != null && userId > 0) {
            User user = userService.getById(userId);
            UserVo userVO = userService.getUserVo(user);
            pictureVO.setUserVo(userVO);
        }
        return pictureVO;
    }

    /**
     * 分页获取图片封装
     *
     * @param picturePage
     * @param request
     * @return
     */
    @Override
    public Page<PictureVO> getPictureVOPage(Page<Picture> picturePage, HttpServletRequest request) {
        List<Picture> pictureList = picturePage.getRecords();
        Page<PictureVO> pictureVoPage = new Page<>(picturePage.getCurrent(), picturePage.getSize(), picturePage.getTotal());

        if (CollUtil.isEmpty(pictureList)) {
            return pictureVoPage;
        }

        List<PictureVO> pictureVOList = pictureList.stream().map(PictureVO::ObjToVo).collect(Collectors.toList());
        Set<Long> idSet = pictureList.stream().map(Picture::getUserId).collect(Collectors.toSet());

        Map<Long, List<User>> longListMap = userService.listByIds(idSet).stream().collect(Collectors.groupingBy(User::getId));

        pictureVOList.forEach(pictureVO -> {
            Long id = pictureVO.getId();
            User user = null;
            if (longListMap.containsKey(id)) {
                user = longListMap.get(id).get(0);
            }
            pictureVO.setUserVo(userService.getUserVo(user));
        });
        pictureVoPage.setRecords(pictureVOList);
        return pictureVoPage;
    }

    @Override
    public void validPicture(Picture picture) {
        ThrowUtils.throwIf(picture == null, ErrorCode.PARAMS_ERROR);
        // 从对象中取值
        Long id = picture.getId();
        String url = picture.getUrl();
        String introduction = picture.getIntroduction();
        // 修改数据时，id 不能为空，有参数则校验
        ThrowUtils.throwIf(ObjUtil.isNull(id), ErrorCode.PARAMS_ERROR, "id 不能为空");
        if (StrUtil.isNotBlank(url)) {
            ThrowUtils.throwIf(url.length() > 1024, ErrorCode.PARAMS_ERROR, "url 过长");
        }
        if (StrUtil.isNotBlank(introduction)) {
            ThrowUtils.throwIf(introduction.length() > 800, ErrorCode.PARAMS_ERROR, "简介过长");
        }
    }


    @Override
    public void doReviewPicture(PictureReviewRequest pictureReviewRequest, User loginUser) {
        Long id = pictureReviewRequest.getId();
        Integer reviewStatus = pictureReviewRequest.getReviewStatus();

        PictureReviewStatusEnum enumsMsg = PictureReviewStatusEnum.getEnumMsgByCode(reviewStatus);
        if (id == null || enumsMsg == null || PictureReviewStatusEnum.REVIEWING.equals(enumsMsg)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }

        Picture picture = this.getById(id);
        Integer oldReviewStatus = picture.getReviewStatus();
        if (oldReviewStatus.equals(reviewStatus)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请勿重复审核");
        }

        Picture updatePicture = new Picture();
        BeanUtils.copyProperties(pictureReviewRequest, updatePicture);
        updatePicture.setReviewerId(loginUser.getId());
        updatePicture.setReviewTime(new Date());
        boolean updated = this.updateById(updatePicture);
        if (!updated) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "操作失败");
        }
    }


    /**
     * 如果是管理员自动补充审核参数
     *
     * @param picture
     * @param loginUser
     */
    @Override
    public void fillReviewParams(Picture picture, User loginUser) {
        String userRole = loginUser.getUserRole();
        if (UserConstant.MUST_ADMIN.equals(userRole)) {
            picture.setReviewStatus(PictureReviewStatusEnum.PASS.getCode());
            picture.setReviewTime(new Date());
            picture.setReviewerId(loginUser.getId());
        } else {
            picture.setReviewStatus(PictureReviewStatusEnum.REVIEWING.getCode());
        }
    }

    @Override
    @Transactional
    public Integer uploadPictureByBatch(PictureUploadByBatchRequest pictureUploadByBatchRequest,
                                        User loginUser) {
        String searchText = pictureUploadByBatchRequest.getSearchText();
        Integer count = pictureUploadByBatchRequest.getCount();
        ThrowUtils.throwIf(count > 30, ErrorCode.PARAMS_ERROR, "最多30条");
        String fetchUrl = String.format("https://cn.bing.com/images/async?q=%s&mmasync=1", searchText);

        Document document = null;
        try {
            document = Jsoup.connect(fetchUrl).get();
        } catch (IOException e) {
            log.error("请求抓取图片失败", e);
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "获取页面失败");
        }
        Element div = document.getElementsByClass("dgControl").first();
        if (ObjectUtil.isNull(div)) {
            throw new BusinessException(ErrorCode.OPERATION_ERROR, "获取元素失败");
        }
        Elements elements = div.select("img.mimg");
        int uploadCount = 0;
        for (Element element : elements) {
            String fileUrl = element.attr("src");
            if (StrUtil.isBlank(fileUrl)) {
                log.info("当前链接为空,跳过：{}", fileUrl);
                continue;
            }
            // 处理图片上传地址，防止出现转义问题
            int questionMarkIndex = fileUrl.indexOf("?");
            if (questionMarkIndex > -1) {
                fileUrl = fileUrl.substring(0, questionMarkIndex);
            }

            String namePrefix = pictureUploadByBatchRequest.getNamePrefix();
            if (StrUtil.isBlank(namePrefix)) {
                namePrefix = searchText;
            }

            // 上传图片
            PictureUploadRequest pictureUploadRequest = new PictureUploadRequest();
            if (StrUtil.isNotBlank(namePrefix)) {
                // 设置图片名称，序号连续递增
                pictureUploadRequest.setPicName(namePrefix + (uploadCount + 1));
            }
            try {
                PictureVO pictureVO = this.uploadPicture(fileUrl, pictureUploadRequest, loginUser);
                log.info("上传图片成功：图片id：{}", pictureVO.getId());
                uploadCount++;
            } catch (Exception e) {
                log.error("上传图片失败：{}", JSONObject.toJSONString(pictureUploadRequest));
                continue;
            }
            if (uploadCount > count) {
                break;
            }
        }
        return uploadCount;
    }

    @Override
    @Async
    public void clearPictureFile(Picture picture) {
        String url = picture.getUrl();
        Long count = this.lambdaQuery().eq(Picture::getUrl, url).count();
        if (count > 1) {
            return;
        }

        // FIXME 这里的 url 包含了域名，实际上只要传 key 值（存储路径）就够了
        cosManager.deleteObject(url);
        // 清理缩略图
        if (StrUtil.isNotBlank(url)) {
            cosManager.deleteObject(picture.getThumbnailUrl());
        }
    }

    /**
     * 用户图片权限校验
     * 只有图片创建者才能删除、编辑
     *
     * @param loginUser
     * @param picture
     */
    @Override
    public void checkPictureAuth(User loginUser, Picture picture) {
        Long spaceId = picture.getSpaceId();
        /*if (spaceId == null) {
            // 公共图库，仅本人或管理员可操作
            if (!picture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        } else {
            // 私有空间，仅空间管理员可操作
            if (!picture.getUserId().equals(loginUser.getId())) {
                throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
            }
        }*/
    }

    @Override
    public boolean deletePicture(DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        User loginUser = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可删除
        if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 权限校验
        checkPictureAuth(loginUser, oldPicture);
        Long spaceId = oldPicture.getSpaceId();
        transactionTemplate.execute(status -> {
            // 操作数据库
            boolean result = this.removeById(id);
            ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);

            // 更新额度
            if (spaceId != null) {
                boolean updated = spaceService.lambdaUpdate().eq(Space::getId, spaceId)
                        .setSql("totalSize = totalSize - " + oldPicture.getPicSize())
                        .setSql("totalCount = totalCount - 1")
                        .update();
                ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "更新额度失败");
            }
            return true;
        });
        this.clearPictureFile(oldPicture);
        return true;
    }

    @Override
    public boolean editPicture(PictureEditRequest pictureEditRequest, HttpServletRequest request) {
        if (pictureEditRequest == null || pictureEditRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 在此处将实体类和 DTO 进行转换
        Picture picture = new Picture();
        BeanUtils.copyProperties(pictureEditRequest, picture);
        // 注意将 list 转为 string
        picture.setTags(JSONUtil.toJsonStr(pictureEditRequest.getTags()));
        // 设置编辑时间
        picture.setEditTime(new Date());
        // 数据校验
        this.validPicture(picture);
        User loginUser = userService.getLoginUser(request);
        this.fillReviewParams(picture, loginUser);
        // 判断是否存在
        long id = pictureEditRequest.getId();
        Picture oldPicture = this.getById(id);
        ThrowUtils.throwIf(oldPicture == null, ErrorCode.NOT_FOUND_ERROR);
        // 仅本人或管理员可编辑
        if (!oldPicture.getUserId().equals(loginUser.getId()) && !userService.isAdmin(loginUser)) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        }
        // 操作数据库
        boolean result = this.updateById(picture);
        ThrowUtils.throwIf(!result, ErrorCode.OPERATION_ERROR);
        return true;
    }

    @Override
    public List<PictureVO> searchPictureByColor(String color, String spaceId, User loginUser) {
        ThrowUtils.throwIf(color == null, ErrorCode.PARAMS_ERROR, "颜色为空");
        ThrowUtils.throwIf(spaceId == null, ErrorCode.PARAMS_ERROR, "空间ID为空");

        // 空间是否存在
        Space space = spaceService.getById(spaceId);
        if (space == null) {
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR, "空间不存在");
        }
        // 检查是否有空间权限
        if (!loginUser.getId().equals(space.getUserId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR, "无空间权限");
        }
        // 查询该空间下的所有图片
        List<Picture> pictureList = this.lambdaQuery().eq(Picture::getSpaceId, spaceId)
                .isNotNull(Picture::getPicColor).list();
        if (!CollUtil.isNotEmpty(pictureList)) {
            return Collections.emptyList();
        }
        // 计算相似度
        Color targetColor = Color.decode(color);
        List<Picture> sortedPictures = pictureList.stream().sorted(Comparator.comparingDouble(picture -> {
            // 提取颜色主色调
            String hexColor = picture.getPicColor();
            // 没有主色调的放在最后
            if (StrUtil.isEmpty(hexColor)) {
                return Double.MAX_VALUE;
            }
            Color picColor = Color.decode(hexColor);
            return -ColorSimilarUtils.calculateSimilarity(targetColor, picColor);
        })).limit(12).collect(Collectors.toList());
        return sortedPictures.stream().map(PictureVO::ObjToVo).collect(Collectors.toList());
    }

    @Override
    @Transactional(rollbackFor = Exception.class)
    public void editPictureByBatch(PictureEditByBatchRequest pictureEditByBatchRequest
            , HttpServletRequest request) {
        List<String> tags = pictureEditByBatchRequest.getTags();
        String category = pictureEditByBatchRequest.getCategory();
        List<Long> pictureIds = pictureEditByBatchRequest.getPictureIds();
        String spaceId = pictureEditByBatchRequest.getSpaceId();
        String nameRule = pictureEditByBatchRequest.getNameRule();

        validateEditBatchParam(tags,category,request,spaceId);

        // 查询出指定的图片
        List<Picture> pictureList = this.lambdaQuery().select(Picture::getId, Picture::getSpaceId)
                .eq(Picture::getSpaceId, spaceId)
                .in(Picture::getId, pictureIds)
                .list();

        if (pictureList.isEmpty()) {
            return;
        }

        fillPictureWithNameRule(pictureList,nameRule);

        int batchSize = 100;
        ArrayList<CompletableFuture<Void>> completableFutures = new ArrayList<>();
        for (int i = 0; i < pictureList.size(); i += batchSize) {
            List<Picture> batchList = pictureList.subList(i, Math.min(i + batchSize, pictureList.size()));
            // 异步处理每批数据
            CompletableFuture<Void> future = CompletableFuture.runAsync(() -> {
                batchList.forEach(picture -> {
                    if (StrUtil.isNotEmpty(category)) {
                        picture.setCategory(category);
                    }

                    if (CollUtil.isEmpty(tags)) {
                        picture.setTags(JSONUtil.toJsonStr(pictureEditByBatchRequest.getTags()));
                    }
                });
                boolean updated = this.updateBatchById(batchList);
                ThrowUtils.throwIf(!updated, ErrorCode.OPERATION_ERROR, "批量更新失败");
            }, threadPoolExecutor);
            completableFutures.add(future);
        }
        // 等待所有任务完成
        CompletableFuture.allOf(completableFutures.toArray(new CompletableFuture[0])).join();
    }

    @Override
    public CreateOutPaintingTaskResponse createOutPaintingTask(OutPaintingAIRequest outPaintingAIRequest,
                                                               User loginUser) {
        long pictureId = outPaintingAIRequest.getPictureId();
        // 查询图片是否存在
        Picture picture = Optional.ofNullable(this.getById(pictureId)).
                orElseThrow(() -> new BusinessException(ErrorCode.NOT_FOUND_ERROR));

        // 权限校验
        checkPictureAuth(loginUser,picture);
        // 调用图片编辑的API
        CreateOutPaintingTaskRequest createOutPaintingTaskRequest = new CreateOutPaintingTaskRequest();
        CreateOutPaintingTaskRequest.Input input = new CreateOutPaintingTaskRequest.Input();
        input.setImageUrl(picture.getUrl());
        createOutPaintingTaskRequest.setInput(input);
        log.info("请求图片编辑的请求类：{}", JSONUtil.toJsonStr(createOutPaintingTaskRequest));
        BeanUtils.copyProperties(outPaintingAIRequest,createOutPaintingTaskRequest);
        return aliYunAiApi.createOutPaintingTask(createOutPaintingTaskRequest);
    }

    /**
     * 参数经验
     * @param tags
     * @param category
     * @param request
     * @param spaceId
     */
    private void validateEditBatchParam(List<String> tags,String category,HttpServletRequest request,String spaceId) {
        ThrowUtils.throwIf(CollectionUtils.isEmpty(tags),ErrorCode.PARAMS_ERROR,"标签参数为空");
        ThrowUtils.throwIf(category == null,ErrorCode.PARAMS_ERROR,"标签参数为空");

        // 校验是否有空间权限
        User loginUser = userService.getLoginUser(request);
        Space space = spaceService.getById(spaceId);
        if (!space.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.NO_AUTH_ERROR,"无空间权限");
        }
    }

    /**
     * 批量重命名图片
     * @param pictureList
     * @param nameRule
     */
    private void fillPictureWithNameRule(List<Picture> pictureList,String nameRule){

        if (StrUtil.isEmpty(nameRule)) {
            return;
        }
        long count = 1;
        try {
            for (Picture picture : pictureList) {
                String replaced = nameRule.replaceAll("\\{序号}", String.valueOf(count++));
                picture.setName(replaced);
            }
        } catch (Exception e) {
            log.error("名称解析错误",e);
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"名称解析失败");
        }
    }
}




